package com.example.keepmesafe.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.List;

import android.os.Environment;
import android.util.Log;

import com.example.keepmesafe.domain.Tag;
import com.example.keepmesafe.service.AESCrypto;
import com.example.keepmesafe.service.DataXmlExporter;
import com.example.keepmesafe.service.Security;

public class DataXmlExporterImpl implements DataXmlExporter {
	private static final String DATASUBDIRECTORY = "keepmesafe";
	private AESCrypto aesCrypto = new AESCrypto();
	@Override
	public String export(List<Tag> tagsToBeExported) throws IOException {
		// TODO Auto-generated method stub
		StringBuilder sb = new StringBuilder();
		sb.append("<?xml version='1.0' encoding='UTF-8'?>");
		sb.append("<tagVault>");
		for(Tag toBeFormattedToXml:tagsToBeExported){
			try {
				sb.append(writeUsingNormalOperation(toBeFormattedToXml));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		sb.append("</tagVault>");
		return writeToFile(sb.toString(),"keep.xml");
	}

	private String writeUsingNormalOperation(Tag tag) throws Exception {
	    String format =
	            "<tag id='%d'>" +
	            " <tagName>%s</tagName> " +
	            " <tagUsername>%s</tagUsername> " +
	            " <tagPassword>%s</tagPassword> " +
	            "</tag> ";
	    return String.format(format,tag.getId(),tag.getTagName(),tag.getTagUsername(),aesCrypto.decrypt(tag.getTagPassword()));
	}
	
	 private String writeToFile(String xmlString, String exportFileName) throws IOException {
		 File dir;
		 if(!Environment.getExternalStorageDirectory().exists()){
			 dir = new File(Environment.DIRECTORY_DOWNLOADS, DATASUBDIRECTORY);
		  }else{
		      dir = new File(Environment.getExternalStorageDirectory(), DATASUBDIRECTORY);
		  }
		  if(!dir.exists())
			  dir.mkdirs();
		  
		  File file = new File(dir, exportFileName);
	      file.createNewFile();

	      ByteBuffer buff = ByteBuffer.wrap(xmlString.getBytes());
	      FileChannel channel = new FileOutputStream(file).getChannel();
	      try {
	         channel.write(buff);
	         Log.i("DataXmlExporterImpl", "written to file successsfully");
	      } finally {
	         if (channel != null)
	            channel.close();
	      }
	      Log.i("DataXmlExporterImpl", "exporting database complete");
	      return Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + DATASUBDIRECTORY + "/" + exportFileName;
	   }
}
